package com.cskaoyan.service;

import com.cskaoyan.anno.LogRecord;
import com.cskaoyan.bean.data.PageData;
import com.cskaoyan.bean.data.GoodsDetailData;
import com.cskaoyan.bean.vo.GoodsCreateVo;
import com.cskaoyan.mapper.*;
import com.cskaoyan.model.*;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    MarketGoodsMapper goodsMapper;
    @Autowired
    MarketGoodsAttributeMapper attributeMapper;
    @Autowired
    MarketGoodsProductMapper productMapper;
    @Autowired
    MarketGoodsSpecificationMapper specificationMapper;
    @Autowired
    MarketCartMapper cartMapper;

    @Autowired
    CategoryService categoryService;
    @Autowired
    BrandService brandService;
    @Autowired
    CommentService commentService;
    @Autowired
    IssueService issueService;
    @Autowired
    CollectionService collectionService;

    @Override
    public PageData query(int page, int limit, String sort, String order) {
        PageHelper.startPage(page, limit);

        MarketGoodsExample example = new MarketGoodsExample();
        example.setOrderByClause(sort + " " + order);
        example.createCriteria().andDeletedEqualTo(false);
        List<MarketGoods> marketGoods = goodsMapper.selectByExample(example);


        return PageData.list(marketGoods);
    }

    @Override
    @Transactional
    @LogRecord
    public boolean createGoods(GoodsCreateVo goodsCreateVo) {
        try {
            //获取当前时间
            Date current = new Date();
            MarketGoods goods = goodsCreateVo.getGoods();
            goods.setAddTime(current);
            goods.setUpdateTime(current);
            goodsMapper.insertSelective(goods);
            Integer goodsId = goods.getId();
            List<MarketGoodsProduct> products = goodsCreateVo.getProducts();
            products.forEach(p->{
                p.setGoodsId(goodsId);
                p.setAddTime(current);
                p.setUpdateTime(current);
                productMapper.insertSelective(p);
            });
            List<MarketGoodsAttribute> attributes = goodsCreateVo.getAttributes();
            attributes.forEach(a->{
                a.setGoodsId(goodsId);
                a.setAddTime(current);
                a.setUpdateTime(current);
                attributeMapper.insertSelective(a);
            });
            List<MarketGoodsSpecification> specifications = goodsCreateVo.getSpecifications();
            specifications.forEach(s->{
                s.setGoodsId(goodsId);
                s.setAddTime(current);
                s.setUpdateTime(current);
                specificationMapper.insertSelective(s);
            });
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    @Override
    public long count() {
        MarketGoodsExample example = new MarketGoodsExample();
        example.createCriteria().andDeletedEqualTo(false);
        long count = goodsMapper.countByExample(example);
        return count;
    }

    @Override
    public List<MarketGoods> goodsList(boolean isHot, boolean isNew, int page, int limit) {
        MarketGoodsExample example = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria = example.createCriteria();
        if (isHot){
            criteria.andIsHotEqualTo(true);
        }if (isNew){
            criteria.andIsNewEqualTo(true);
        }
        example.setOrderByClause("add_time desc");
        PageHelper.startPage(page,limit);
        List<MarketGoods> marketGoods = goodsMapper.selectByExample(example);
        return marketGoods;
    }

    @Override
    public List floorGoodsList(int categoryLimit, int categoryGoodsLimit) {
        List<Map> categoryList = new ArrayList<>();
        List<MarketCategory> catL1List=categoryService.list("L1",1,categoryLimit);
        for (MarketCategory catL1 : catL1List) {
            Map<String,Object> catGoods=new HashMap<>();
            Integer categoryId = catL1.getId();
            List<MarketGoods> categoryGoods=list(categoryId,1,categoryLimit);
            catGoods.put("id",categoryId);
            catGoods.put("name",catL1.getName());
            catGoods.put("goodsList",categoryGoods);
            categoryList.add(catGoods);
        }
        return categoryList;
    }

    private List<MarketGoods> list(Integer categoryId, int page, int limit) {
        List<MarketGoods>goodsList=new ArrayList<>();
        MarketCategory category=categoryService.findById(categoryId);
        if (category==null){
            return goodsList;
        }
        if ("L1".equals(category.getLevel())){
            List<MarketCategory> marketCategories=categoryService.queryChildren(categoryId);
            List<Integer> l2CategoryIds = marketCategories.stream().map(MarketCategory::getId).collect(Collectors.toList());
            MarketGoodsExample example = new MarketGoodsExample();
            example.createCriteria().andDeletedEqualTo(false)
                    .andCategoryIdIn(l2CategoryIds);
            goodsList=goodsMapper.selectByExample(example);
        }
        if ("L2".equals(category.getLevel())){
            MarketGoodsExample example = new MarketGoodsExample();
            example.createCriteria().andDeletedEqualTo(false)
                    .andCategoryIdEqualTo(categoryId);
            PageHelper.startPage(page,limit);
            goodsList= goodsMapper.selectByExample(example);
        }
        return goodsList;
    }

    @Override
    public GoodsDetailData detail(Integer goodsId, int userId) {
        MarketGoods marketGoods = goodsMapper.selectByPrimaryKey(goodsId);
        List<MarketGoodsAttribute> attributes= this.getAttributes(goodsId);
        List<MarketGoodsProduct>productList=this.getProducts(goodsId);
        List<Map> specificationList=this.getSpecifications(goodsId);

        //market——goods和brand之间的关系，market_goods表中有个brand_id字段
        Integer brandId = marketGoods.getBrandId();
        MarketBrand marketBrand= brandService.findById(brandId);

        //封装comment：当前商品评论的数量和前俩条数据
        //传入了goodsId和评论的类型（tinyint->byte）

        Map<String,Object>commentMap=commentService.findById(goodsId,(byte)0,1,2);

        //issue->所有的常见问题
        List<MarketIssue>issues=issueService.all();
        //userHasCollecton->用户是否有收藏-》用户id，商品id，收藏类型
        Integer userHasCollection = collectionService.hasCollection(goodsId,(byte)0,userId);
        GoodsDetailData data = GoodsDetailData.builder()
                .attribute(attributes)
                .productList(productList)
                .specificationList(specificationList)
                .brand(marketBrand)
                .info(marketGoods)
                .comment(commentMap)
                .issue(issues)
                .userHasCollection(userHasCollection)
                .share(true)
                .shareImage("")
                .build();
        return data;
    }

    @Override
    public MarketGoods findById(Integer id) {
        MarketGoodsExample example = new MarketGoodsExample();
        example.createCriteria().andIdEqualTo(id)
                .andDeletedEqualTo(false);
        List<MarketGoods> goodsList = goodsMapper.selectByExample(example);
        return goodsList!=null&&goodsList.size()==1?goodsList.get(0):null;
    }

    @Override
    public PageData queryByCategory(Integer categoryId, int page, int related) {
        MarketGoodsExample example = new MarketGoodsExample();
        example.createCriteria().andCategoryIdEqualTo(categoryId)
                .andDeletedEqualTo(false);
        example.setOrderByClause("add_time desc");
        PageHelper.startPage(page,related);
        List<MarketGoods> goodsList = goodsMapper.selectByExample(example);
        return PageData.list(goodsList);
    }

    // @Override
    // public List<MarketGoods> getCheckGoodsList(List<MarketCart> cartList) {
    //     List<MarketGoods> checkGoodsList=new ArrayList<>();
    //     List<Integer> goodsIdList = cartList.stream().filter(MarketCart::getChecked).map(MarketCart::getGoodsId).toList();
    //     goodsIdList.forEach(t->{
    //         MarketGoods marketGoods = goodsMapper.selectByPrimaryKey(t);
    //         checkGoodsList.add(marketGoods);
    //     });
    //     return checkGoodsList;
    // }

    @Override
    public List<MarketGoods> queryByCartId(Integer cartId) {
        MarketCart marketCart = cartMapper.selectByPrimaryKey(cartId);
        Integer goodsId = marketCart.getGoodsId();
        MarketGoodsExample example = new MarketGoodsExample();
        example.createCriteria()
                .andIdEqualTo(goodsId)
                .andDeletedEqualTo(false);
        List<MarketGoods> marketGoodsList = goodsMapper.selectByExample(example);


        return marketGoodsList;
    }

    private List<Map> getSpecifications(Integer goodsId) {
        MarketGoodsSpecificationExample example = new MarketGoodsSpecificationExample();
        example.createCriteria().andGoodsIdEqualTo(goodsId)
                .andDeletedEqualTo(false);
        example.setOrderByClause("add_time desc");
        List<MarketGoodsSpecification> specificationList = specificationMapper.selectByExample(example);
        Map<String, List<MarketGoodsSpecification>> collect = specificationList.stream().collect(Collectors.groupingBy(MarketGoodsSpecification::getSpecification));
        List<Map> specificationMapList=new ArrayList<>();
        for (String name : collect.keySet()) {
            HashMap<Object,Object>map=new HashMap<>();
            map.put("name",name);
            map.put("valueList",collect.get(name));
            specificationMapList.add(map);
        }
        return specificationMapList;
    }

    private List<MarketGoodsProduct> getProducts(Integer goodsId) {
        MarketGoodsProductExample example = new MarketGoodsProductExample();
        example.createCriteria().andGoodsIdEqualTo(goodsId)
                .andDeletedEqualTo(false);
        example.setOrderByClause("add_time desc");
        return productMapper.selectByExample(example);
    }

    private List<MarketGoodsAttribute> getAttributes(Integer goodsId) {
        MarketGoodsAttributeExample example = new MarketGoodsAttributeExample();
        example.createCriteria().andGoodsIdEqualTo(goodsId)
                .andDeletedEqualTo(false);
        example.setOrderByClause("add_time desc");
        return attributeMapper.selectByExample(example);
    }


}
